import { UserType } from "../entity/enum/userType.enum";
import { Store } from "../main";

/**
 * 路由禁用
 */
const DisabledRouting = {
  [UserType.普通用户]: [] as string[],
  [UserType.会员用户]: [] as string[],
  [UserType.超级会员]: [] as string[],
};

/**
 * 获取禁用路由
 */
const getDisabledRouting = () => {
  return DisabledRouting[Store.User.getUserInfo().userType];
};

/**
 * 权限字典
 */
const AuthDic = {
  CREATE: 0b0001,
  DELETE: 0b0010,
  UPDATE: 0b0100,
  DETAIL: 0b1000,
};

/**
 * 权限控制
 */
const UserAuthDic = {
  [UserType.普通用户]: AuthDic.DETAIL,
  [UserType.会员用户]: AuthDic.DETAIL | AuthDic.UPDATE,
  [UserType.超级会员]: AuthDic.DETAIL | AuthDic.UPDATE | AuthDic.CREATE | AuthDic.DELETE,
};

/**
 * 判断用户是否有该权限
 * @param authNum 权限值：来自于AuthDic的key或者value
 */
const hasAuth = (authNum: number | string) => {
  let auth = 0;
  typeof authNum === "number" && (auth = authNum);
  typeof authNum === "string" && (auth = AuthDic[authNum]);
  return (UserAuthDic[Store.User.getUserInfo().userType] & auth) === auth;
};

/**
 * 获取用户权限
 */
const getAuth = () => {
  const result = [];
  for (const key in AuthDic) {
    if (hasAuth(AuthDic[key])) result.push(key);
  }
  return result;
};

/**
 * 挂载全局的Auth
 * @returns Auth
 */
const CreateAuth = () => {
  return {
    hasAuth,
    getAuth,
  };
};
export { getDisabledRouting };
export default CreateAuth;
